package kassiopeia.agent.alerting;

import kassiopeia.agent.AgentIDHolder;
import kassiopeia.commons.exception.SedaException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;

@Component
public class Alerting {

    @Autowired
    private AlertingTimer engine;

    public static String exToString(Exception ex) {
        if (ex == null)
            return "";
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        PrintStream ps = new PrintStream(os);
        ex.printStackTrace(ps);
        ps.close();
        try {
            return os.toString("UTF-8");
        } catch (UnsupportedEncodingException e) {
            return os.toString();
        }
    }

    private void alert(Alert alert) {
        engine.alert(alert);
    }

    public void alertInternalError(String message, Exception ex) {
        alert(new Alert(AlertType.INTERNAL_ERROR, message, exToString(ex)));
    }

    public void alertAgentStarted() {
        String msg = "Agent with id " + AgentIDHolder.getThisAgentId() + " has been started";
        alert(new Alert(AlertType.AGENT_STARTED, msg));
    }

    public void alertSedaError(SedaException ex) {
        alert(new Alert(AlertType.SEDA_ERROR, "SEDA error occured", exToString(ex)));
    }

    public void alertStagePoolExhausted(String message) {
        alert(new Alert(AlertType.STAGE_POOL_EXHAUSTED, message));
    }

    public void alertPluginMessage(String message) {
        alert(new Alert(AlertType.PLUGIN_ALERT, message));
    }

    public void alertPluginError(Exception e, String message) {
        alert(new Alert(AlertType.PLUGIN_ERROR, message, exToString(e)));
    }
}
